//
//  HMOAuthViewController.swift
//  weibo28
//
//  Created by 范英强 on 16/3/23.
//  Copyright © 2016年 范英强. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class HMOAuthViewController: UIViewController {
    
    override func loadView() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        view = webView
        webView.delegate = self
        webView.loadRequest(request)
    }

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    
    // 设置视图
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: UIBarButtonItemStyle.Plain, target: self, action: "AutoFill")
        
        navigationItem.title = "OAuth授权"
        
    }
    
    // MARK: - 监听方法
    
    @objc private func cancel(){
       // dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func AutoFill(){
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value='18911412662';document.getElementById('passwd').value='19880828'")
    }
    
    // MARK: - 懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    // MARK: - 得了accessToken
    func loadAccessToken(code: String){
        // 请求的url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 请求参数
        let parms = [
            "client_id":AppKey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":Redirect_uri
        ]
        
        let AFN = AFHTTPSessionManager()
        // 插入text/plain
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        // afn post请求
        AFN.POST(urlString, parameters: parms, progress: nil, success: { (_, response) -> Void in
            // guard let  if let 使用as转数据时候 使用as?
            guard let dict = response as? [String: AnyObject] else{
                print("返回的数据不是字典")
                return
            }
            
            
            let account = HMUserAccount(dict: dict)
            
            // 请求个人信息数据接口

            self.loadUserInfo(account)

            }) { (_, error) -> Void in
                print("失败的\(error)")
        }
        
    }
    // MARK: - 请求用户个人信息
    func loadUserInfo(account:HMUserAccount){
        // 请求urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token":account.access_token!,
            "uid":account.uid!
        ]
        
        let manager = AFHTTPSessionManager()
        
        manager.GET(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
            
            guard let dict = response as?[String:AnyObject] else{
                print("返回的数据不是字典")
                return
            }
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            // 通过归档保存用户数据
            HMUserAccountTools.sharedTools.saveUserAccount(account)
            
            
            //
            /**
            *
            1.关闭当前页面
            2.跳到欢迎页面
            */
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                // 发送通知 
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVcNotification, object: "oauth")
            })
            

            }) { (_, error) -> Void in
               print("失败\(error)")
        }

    }
    

    

}

extension HMOAuthViewController:UIWebViewDelegate{
    
    // 监听webView将要加载的地址 默认加载将要加载的地址 返回时true
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        // 判断url是否存在
        guard let urlString = request.URL?.absoluteString else{
            return false
        }

        // 判断url的前缀是我们的回调页
        if urlString.hasPrefix(Redirect_uri){
            // 判断参数是否存在
            guard let query = request.URL?.query else{
                return false
            }
            // 得到code
            let code = query.substringFromIndex("code=".endIndex)
            
            // 请求接口得到accessToken
            loadAccessToken(code)
            
            return false
        }
        
        
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
